package com.jboost.common.delayed;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Executors;

@Component
@Slf4j
public class DelayQueueManagers implements CommandLineRunner {

    private final DelayQueue<DelayTask> delayQueue = new DelayQueue<>();
    @Autowired(required = false)
    Map<String, IDelayHandler> handlerMap;

    /**
     * 加入到延时队列中
     * @param task
     */
    public void put(DelayTask task) {
        log.error("加入延时任务：{}", task);
        delayQueue.put(task);
    }
    /**
     * 取消延时任务
     * @param task
     * @return
     */
    public boolean remove(DelayTask task) {
        log.error("取消延时任务：{}", task);
        return delayQueue.remove(task);
    }

    /**
     * 取消延时任务
     * @param taskid
     * @param handlerName
     * @return
     */
    public boolean remove(String taskid,String handlerName) {
        return remove(new DelayTask(new TaskBase(taskid,handlerName), 0));
    }
    @Override
    public void run(String... args) throws Exception {
        log.info("初始化延时队列");
        Executors.newSingleThreadExecutor().execute(new Thread(this::excuteThread));
    }
    /**
     * 延时任务执行线程
     */
    private void excuteThread() {
        while (true) {
            try {
                DelayTask task = delayQueue.take();
                processTask(task);
            } catch (InterruptedException e) {
                break;
            }
        }
    }
    /**
     * 内部执行延时任务
     * @param task
     */
    private void processTask(DelayTask task) {
        log.error("执行延时任务：{}-{}", task,task.getData().getIdentifier());
        IDelayHandler handler = handlerMap.get(task.getData().getHandlerName());
        if(null!=handler){
            try{
                handler.execute(task);
            }catch (Exception e){
                log.error("延时任务出错：", e.getMessage());
            }
        }else {
            log.error("找不到对应的handler："+task.getData().getHandlerName());
        }
    }
}


